package com.blog.admin.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.blog.admin.service.FileInfoService;
import com.blog.common.domain.entity.FileInfo;
import com.blog.common.domain.vo.FileInfoVo;
import com.blog.common.mapper.dao.FileInfoMapper;
import com.blog.common.redis.service.RedisService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.blog.common.core.constant.CacheConstants.*;
import static com.blog.common.core.constant.ServiceConst.IS_FALSE;

/**
 * <p>
 * 文件 服务实现类
 * </p>
 *
 * @author Valerie
 * @since 2023-03-11
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class FileInfoServiceImpl extends ServiceImpl<FileInfoMapper, FileInfo> implements FileInfoService {


    private final FileInfoMapper fileInfoMapper;

    private final RedisService redisService;


    @Override
    public void refreshFileInfoList(String key){
        List<FileInfo> fileInfoList = fileInfoMapper.selectList(null);
        if (CollectionUtil.isEmpty(fileInfoList)){
            return;
        }
        Map<Long, String> fileInfoMap = fileInfoList.stream().collect(Collectors.toMap(FileInfo::getId, f -> f.getCdnPath() + f.getFilePath()));
        redisService.del(PAGE_COVER, WEBSITE_CONFIG, key);
        redisService.hPutAll(key, fileInfoMap);
        redisService.expire(key, 30L, TimeUnit.MINUTES);
        log.warn("定时任务->{}", "刷新图片缓存");
    }

    @Override
    public List<FileInfoVo> listFileInfo() {
        List<FileInfo> fileInfoList = this.list(new LambdaQueryWrapper<FileInfo>()
                .eq(FileInfo::getFileName, "定时任务")
                .eq(FileInfo::getStatus, IS_FALSE));
        return BeanUtil.copyToList(fileInfoList, FileInfoVo.class);
    }
}
